package sina.girl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.th.spider.Config;
import com.th.spider.URLUtil;

public class SavePic {
    private static final Log log = LogFactory.getLog(SavePic.class);
    
    /**
     * sina/pageid/图集/图片
     * 一个图集就是一个list
     * @param list
     * @throws Exception
     */
    public void save(List<List<Map<String, String>>> list) throws Exception {
        log.info("save start");
        if (null != list && list.size() > 0) {
            Iterator<List<Map<String, String>>> iter = list.iterator();
            int num = 0;
            while (iter.hasNext()) {
                List<Map<String, String>> picList = iter.next();
                for (int i = 0; i < picList.size(); i++) {
                    Map<String, String> picMap = picList.get(i);
                    String picName = picMap.get("picname");//图集名字
                    String picPath = picMap.get("picpath");//图片URL
                    log.info(picName);
                    
                    log.info(picPath);
                    log.info("----------");
                    savePic(picName, i + picPath.substring(picPath.length() - 4, picPath.length()),
                            String.valueOf(num), picPath);
                }
                num++;
            }
        }
        log.info("save end");
    }
    
    /**
     * 
     * @param picListName 图集名称
     * @param fileName 图片名称
     * @param pageId 页ID
     * @param url 图片URL
     * @throws Exception
     */
    public static void savePic(String picListName, String fileName, String pageId, String url) throws Exception {
        String dir = getDir(picListName, pageId);
        String file = dir + "/" + fileName;
        BufferedOutputStream out = null;
        byte[] bit = URLUtil.getByte(url);
        if (bit.length > 0) {
            try {
                out = new BufferedOutputStream(new FileOutputStream(file));
                out.write(bit);
                out.flush();
                log.info("Create File success! [" + file + "]");
            } finally {
                if (out != null)
                    out.close();
            }
        }
    }
    
    /**
     * 
     * @param pageId 页数
     * @param dirName 图集名字
     * @return
     */
    private static String getDir(String pageId, String dirName) {
        String pagePath = Config.getSinaProps("sina.save.dir") + "/" + pageId;
        File pageDir = new File(pagePath);
        if (!pageDir.exists()) {
            pageDir.mkdirs();
        }
        String filePath = pagePath + "/" + dirName;
        File fileDir = new File(filePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        return filePath;
    }
}